package comm;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;

public class NetworkInterfaceHandler {


	final private static NetworkInterfaceHandler instance = new NetworkInterfaceHandler();
	
	private ArrayList<NetworkInterface> nics;
	private NetworkInterfaceHandler(){
		
		MulticastSocket socket;
		try{
			Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();     
			nics = new ArrayList<NetworkInterface>();     
			while (nis.hasMoreElements()) {         
				NetworkInterface ni = (NetworkInterface) nis.nextElement();
				//System.out.println("Looking at nic: " + ni.getDisplayName());
				if (
						!ni.isLoopback() && 
						!ni.isPointToPoint() && 
						!ni.isVirtual() && 

						ni.isUp() && 
						ni.supportsMulticast()) {                 
					//System.out.println("adding nic: " + ni.getDisplayName());
					
					//test nics
					try{
						socket = new MulticastSocket();
						socket.setNetworkInterface(ni);
						nics.add(ni);
					}
					catch (Exception e){
						//do nothing
					}
				}                             
			}
			/*
			System.out.println("nics supporting multicast: ");
			for (NetworkInterface nic : nics){
				System.out.println(nic.getDisplayName());
			}
			*/
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public ArrayList<NetworkInterface> getNics(){
		return nics;
	}
	
	public static NetworkInterfaceHandler getInstance(){
		return instance;
	}

}
